package com.kiss.rpc.channelhandler.handler;

import com.kiss.rpc.RpcBootstrap;
import com.kiss.rpc.enumeration.ResponseCode;
import com.kiss.rpc.exceptions.ResponseException;
import com.kiss.rpc.protection.CircuitBreaker;
import com.kiss.rpc.transport.message.RpcResponse;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;

import java.net.SocketAddress;
import java.util.Map;
import java.util.concurrent.CompletableFuture;

@Slf4j
public class MySimpleChannelInboundHandler extends SimpleChannelInboundHandler<RpcResponse> {

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, RpcResponse rpcResponse) {
        CompletableFuture<Object> completableFuture = RpcBootstrap.PENDING_REQUEST.get(rpcResponse.getRequestId());

        SocketAddress socketAddress = channelHandlerContext.channel().remoteAddress();

        Map<SocketAddress, CircuitBreaker> everyIpCircuitBreaker = RpcBootstrap.getInstance()
                .getConfig().getEveryIpCircuitBreaker();
        CircuitBreaker circuitBreaker = everyIpCircuitBreaker.get(socketAddress);

        byte code = rpcResponse.getCode();
        if (code == ResponseCode.SUCCESS.getCode()) {
            Object res = rpcResponse.getBody();
            completableFuture.complete(res);
            if (log.isDebugEnabled()) {
                log.debug("已经寻找到编号为【{}】的completableFuture，处理响应结果", rpcResponse.getRequestId());
            }
        }
        else if (code == ResponseCode.RATE_LIMIT.getCode()){
            circuitBreaker.recordErrorRequest();
            completableFuture.complete(null);
            log.error("当前id为[{}]的请求，被限流，响应码[{}].",
                    rpcResponse.getRequestId(),rpcResponse.getCode());
            throw new ResponseException(code, ResponseCode.RATE_LIMIT.getDesc());
        }
        else {
            completableFuture.complete(null);
            throw new ResponseException(code, ResponseCode.RATE_LIMIT.getDesc());
        }
    }
}
